package cn.wp.user.service.impl;

import cn.wp.basic.exception.CustomException;
import cn.wp.basic.util.AjaxResult;
import cn.wp.basic.util.MD5Utils;
import cn.wp.user.domain.LoginInfo;
import cn.wp.user.mapper.LoginInfoMapper;
import cn.wp.user.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult login(LoginInfo loginInfo) throws CustomException {
        // 验证数据
        chenkDate(loginInfo);
        // 通过oginInfo查询
        LoginInfo info = loginInfoMapper.loadByUsernameOrEmailOrPhoneAndType(loginInfo);
        // 验证密码
        if (!info.getPassword().equals(MD5Utils.encrypByMd5(loginInfo.getPassword()+info.getSalt()))){
            throw new CustomException("密码错误！");
        }
        // 生成token
        String token = UUID.randomUUID().toString();
        // token保存到redis
        redisTemplate.opsForValue().set(token, info,30, TimeUnit.MINUTES);

        Map<String,Object> map = new HashMap<>();
        // 保存token
        map.put("token", token);
        // 保存登录信息
        map.put("loginUser", info);
        // 返回前端
        return AjaxResult.me().setResultObject(map);
    }

    private void chenkDate(LoginInfo loginInfo) throws CustomException {
        if (StringUtils.isEmpty(loginInfo.getUsername())){
            throw new CustomException("账户不能为空！");
        }
        if (StringUtils.isEmpty(loginInfo.getPassword())){
            throw new CustomException("密码不能为空！");
        }
        if (loginInfo.getType()==null){
            throw new CustomException("请完善信息！");
        }
    }
}
